package cn.tedu.mall.order.service.impl;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.domain.CsmallAuthenticationInfo;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.front.service.IFrontSkuService;
import cn.tedu.mall.order.service.IOmsCartService;
import cn.tedu.mall.pojo.order.dto.CartAddDTO;
import cn.tedu.mall.pojo.order.dto.CartUpdateDTO;
import cn.tedu.mall.pojo.order.vo.CartStandardVO;
import cn.tedu.mall.pojo.product.vo.SkuStandardVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
@Slf4j
public class CartServiceImpl implements IOmsCartService {

    public static final String ORDER_CART_PREFIX = "cart:user:";

    @Autowired
    @Qualifier(value = "redisTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private IFrontSkuService dubboSkuService;
    @Autowired
    private UserInfo userInfo;

    /**
     *
     * @param cartDTO
     */
    @Override
    public void addCart(CartAddDTO cartDTO) {
        Long userId = userInfo.getUserId();
        HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
        String cartKey = ORDER_CART_PREFIX + userId;
        Boolean existCart = hashOperations.hasKey(cartKey, cartDTO.getSkuId() + "");
        SkuStandardVO sku = dubboSkuService.getSku(cartDTO.getSkuId());
        if (cartDTO.getQuantity() > 200) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "单件商品个数禁止超过200个");
        }
        if (existCart) {
            if (sku.getStock() < cartDTO.getQuantity()) {
                throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "库存不足！");
            }
            Integer numOfSku = Integer.parseInt(Objects.requireNonNull(hashOperations.get(cartKey, cartDTO.getSkuId() + "")));
            if (cartDTO.getQuantity() + numOfSku > 200) {
                throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "单件商品个数禁止超过200个");
            }
            // 使对应key的value值增加 cartDTO.getQuantity() 这么多
            hashOperations.increment(cartKey, cartDTO.getSkuId() + "", cartDTO.getQuantity());
        } else {
            Long size = hashOperations.size(cartKey);
            if (size == 20) {
                throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "购物车已满！");
            }
            if (sku == null) {
                throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "商品不存在！");
            }
            if (sku.getStock() < cartDTO.getQuantity()) {
                throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "库存不足！");
            }
            hashOperations.put(cartKey, cartDTO.getSkuId() + "", cartDTO.getQuantity() + "");
        }
    }

    @Override
    public JsonPage<CartStandardVO> listCarts(Integer page, Integer pageSize) {
        String cartKey = ORDER_CART_PREFIX + userInfo.getUserId();
        HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
        Boolean existCart = stringRedisTemplate.hasKey(cartKey);
        if (!existCart) {
            log.error("购物车不存在,cartKey:{}", cartKey);
            return JsonPage.nullPage();
        } else {
            Set<String> keys = hashOperations.keys(cartKey);
            if (keys.isEmpty()) {
                log.error("购物车为空,cartKey:{}", cartKey);
                return JsonPage.nullPage();
            }
            List<Long> skuIds = new ArrayList<>();
            for (String key : keys) {
                Long skuId = Long.parseLong(key);
                skuIds.add(skuId);
            }
            List<SkuStandardVO> skuStandardVOS = dubboSkuService.listSkuByIds(skuIds);
            List<CartStandardVO> cartStandardVOS = new ArrayList<>();
            for (SkuStandardVO skuStandardVO : skuStandardVOS) {
                CartStandardVO cartStandardVO = new CartStandardVO();
                // 相同数据替换
                cartStandardVO.setBarCode(skuStandardVO.getBarCode());
                cartStandardVO.setTitle(skuStandardVO.getTitle());
                cartStandardVO.setPrice(skuStandardVO.getPrice());
                // 特殊数据替换
                cartStandardVO.setSkuId(skuStandardVO.getId());
                cartStandardVO.setData(skuStandardVO.getSpecifications());
                cartStandardVO.setMainPicture(skuStandardVO.getPictures().split(",")[0]);
                //本地计算封装的
                cartStandardVO.setQuantity(Integer.parseInt(Objects.requireNonNull(hashOperations.get(cartKey, skuStandardVO.getId() + ""))));
                cartStandardVO.setUserId(userInfo.getUserId());
                cartStandardVO.setId(cartStandardVO.getUserId() + ":" + cartStandardVO.getSkuId());
                cartStandardVOS.add(cartStandardVO);
            }
            return JsonPage.defaultPage(cartStandardVOS);
        }
    }

    @Override
    public void updateQuantity(CartUpdateDTO cartUpdateDTO) {
        String id = cartUpdateDTO.getId();
        Integer quantity = cartUpdateDTO.getQuantity();
        if (quantity > 200) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "单件商品个数禁止超过200个");
        }
        Long userId = Long.parseLong(id.split(":")[0]);
        Long skuId = Long.parseLong(id.split(":")[1]);
        if (userId.equals(userInfo.getUserId())) {
            HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
            String cartKey = ORDER_CART_PREFIX + userId;
            Boolean existCart = hashOperations.hasKey(cartKey, skuId + "");
            if (existCart) {
                SkuStandardVO sku = dubboSkuService.getSku(skuId);
                if (sku.getStock() < quantity) {
                    throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "库存不足！");
                } else {
                    hashOperations.put(cartKey, skuId + "", quantity + "");
                }
            } else {
                throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "购物车不存在");
            }
        } else {
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,"登录用户和购物车用户不一致");
        }
    }

}
